package cn.buddha.jesj.io.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @ClassName NioTest
 * @Author 友野浩二
 * @Date 2019/11/18 20:19
 * @Description NIO(同步 、 非阻塞)
 * @Version 1.0
 * <pre>
 *      Channel是双向的，既可以读又可以写;
 *      对Channel的读写必须通过Buffer对象。
 * </pre>
 */
@Slf4j
public class NioTest {

    private static final String SOURCE_FILE = "E:\\study\\files\\haha.txt";
    private static final String DEST_FILE = "E:\\study\\files\\heihei.txt";

    public static void main(String[] args) {
        copyFileUseNIO(SOURCE_FILE, DEST_FILE);
    }

    public static void copyFileUseNIO(String source, String dest) {
        File sourceFile = new File(source);
        File destFile = new File(dest);

        try (
                // 声明源文件和目标文件
                FileInputStream fileIs = new FileInputStream(sourceFile);
                FileOutputStream fileOs = new FileOutputStream(destFile);

                // 获得传输通道channel
                FileChannel inChannel = fileIs.getChannel();
                FileChannel outChannel = fileOs.getChannel();
        ) {
            // 获得容器buffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            while (Boolean.TRUE) {
                // 判断是否读完文件
                int eof = inChannel.read(byteBuffer);// 从文件通道读取字节到buffer
                if (eof == -1) {
                    break;
                }
                System.out.println(byteBuffer);
                // 切换buffer从写模式到读模式: 重设一下buffer的position=0，limit=position.
                byteBuffer.flip();
                // 开始写
                outChannel.write(byteBuffer);
                // 清空缓冲区。写完要重置byteBuffer，重设position=0,limit=capacity
                byteBuffer.clear();
            }
        } catch (IOException e) {
            log.info("文件拷贝异常: ", e);
        }
    }

}
